#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <unistd.h>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>

#include "log.hpp"

using std::string;

class Sock
{
private:
    // 将listen的第二个参数设为1
    const static int gbacklog = 1; // 监听队列的最大数量
public:
    Sock() {}
    ~Sock() {}

    static int Socket() // 创建监听socket
    {
        int listenSock = socket(AF_INET, SOCK_STREAM, 0);
        if(listenSock < 0) // 失败
        {
            logMessage(FATAL, "socket error");
            exit(2);
        }
        logMessage(NORMAL, "create socket successfully");
        return listenSock;
    }

    static void Bind(int sock, uint16_t port, string ip = "0.0.0.0")
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        // local.sin_addr.s_addr = inet_addr(ip.c_str());
        inet_pton(AF_INET, ip.c_str(), &local.sin_addr);
        if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind error | %d : %s", errno, strerror(errno));
            exit(3);
        }
    }

    static void Listen(int sock)
    {
        if(listen(sock, gbacklog) < 0)
        {
            logMessage(FATAL, "listen error | %d : %s", errno, strerror(errno));
            exit(4);
        }
        logMessage(NORMAL, "init server successfully");
    }

    static int Accept(int sock, string* ip, uint16_t* port)
    {
        // 接收连接请求
        struct sockaddr_in src;
        socklen_t len = sizeof(src);
        int serviceSock = accept(sock, (struct sockaddr*)&src, &len);
        if(serviceSock < 0)
        {
            logMessage(FATAL, "accept error | %d : %s", errno, strerror(errno));
            exit(5);
        }
        if(port) *port = ntohs(src.sin_port);
        if(ip) *ip = inet_ntoa(src.sin_addr);
        return serviceSock;
    }

    // 连接
    static bool Connect(int sock, const string& server_ip, const uint16_t& server_port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(server_port);
        server.sin_addr.s_addr = inet_addr(server_ip.c_str());
        if(connect(sock, (struct sockaddr*)&server, sizeof(server)) == 0)
        {
            logMessage(NORMAL, "connect to %s successfully", server_ip.c_str());
            return true;
        }
        else
            return false;

    }

    // 主动关闭连接
    void Close(int sock)
    { }
};